/*
 * FormPrincipal.java
 * 
 * Created on 03/03/2009, 10:31:46
 */
package forms;

import htmlparser.HtmlParser;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.JFileChooser;
import nameparser.ParseException;
import nameparser.NameParser;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

/**
 *
 * @author ADANIYA
 */
public class FormPrincipal extends javax.swing.JFrame {
    static private final String newline = "\n";
    private JFileChooser filechooser;
    private NameParser nameParser;
    InputStream inputStream = null;
    private HtmlParser htmlParser;
    private NodeList nodeList, nodeListParagraph;

    /** Creates new form FormPrincipal */
    public FormPrincipal() {
        initComponents();
        this.setLocationRelativeTo(this);
        filechooser = new JFileChooser();
        //filechooser.setVisible(false);
        //txtLog.append("> " + System.getProperty("user.dir") + newline);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtURL = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtLog = new javax.swing.JTextArea();
        jLabel2 = new javax.swing.JLabel();
        btnAbrir = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtNomes = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Salus Parser for Named Entity Recognition");

        jLabel1.setText("URL:");

        txtLog.setColumns(20);
        txtLog.setEditable(false);
        txtLog.setRows(5);
        jScrollPane1.setViewportView(txtLog);

        jLabel2.setText("Nomes:");

        btnAbrir.setText("Abrir");
        btnAbrir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAbrirActionPerformed(evt);
            }
        });

        txtNomes.setColumns(20);
        txtNomes.setEditable(false);
        txtNomes.setRows(5);
        jScrollPane2.setViewportView(txtNomes);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 426, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 426, Short.MAX_VALUE)
                    .addComponent(txtURL, javax.swing.GroupLayout.DEFAULT_SIZE, 426, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addComponent(btnAbrir, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtURL, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAbrir))
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    @SuppressWarnings("static-access")
    private void btnAbrirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAbrirActionPerformed
        byte[] bytes;
        ByteArrayInputStream byteArrayInputStream;
        ArrayList arrayList = new ArrayList();
        txtNomes.setText("");
        if (evt.getSource() == btnAbrir) {
            txtNomes.setText("");
            int returnVal = filechooser.showOpenDialog(FormPrincipal.this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = filechooser.getSelectedFile();
                txtURL.setText(file.getAbsolutePath().toString());
                txtLog.append("> Abrindo: " + file.getName() + "." + newline);
                txtLog.append("> " + file.getAbsolutePath().toString() + newline);

                try {
                    htmlParser = new HtmlParser(file.getAbsolutePath().toString());
                    txtLog.append("> HTML parser. " + newline);
                    nodeList = htmlParser.getNodeList();
                    htmlParser.percorrerAllHtml(nodeList);
//                    htmlParser.percorrerAllAuthorTagHtml(nodeList);
                    htmlParser.getString().getBytes();
                    //htmlParser.percorrerHtml();
                    if (inputStream == null){
                        bytes = htmlParser.getString().getBytes();
                        byteArrayInputStream = new ByteArrayInputStream(bytes);
                        inputStream = byteArrayInputStream;
                        nameParser = new NameParser(inputStream);
//                        inputStream = new FileInputStream(file);
//                        nameParser = new NameParser(inputStream);
                    }else{
                        bytes = htmlParser.getString().getBytes();
                        byteArrayInputStream = new ByteArrayInputStream(bytes);
                        inputStream = byteArrayInputStream;
//                        nameParser = new NameParser(inputStream);
//                        inputStream = new FileInputStream(file);
                        nameParser.ReInit(inputStream);                        
                    }

                    //A partir daqui que o nameParser trabalha mesmo.
                    try {
                        nameParser.Input();
                    } catch (ParseException ex) {
                        txtLog.append(newline + "ERRO:" + ex.getMessage());
                    }

                    txtLog.append("> NameParser. " + newline);
                    txtLog.append("> Nomes Encontrados = " + String.valueOf(nameParser.getContador()) + newline);
                    nameParser.zerarContador();
                    arrayList = nameParser.getNomes();
                    if(arrayList.isEmpty()){
                        txtLog.append("> LISTA VAZIA. " + newline);
                    }else{
                        txtLog.append("> LISTA CHEIA. " + newline);
                        for (Iterator it = arrayList.iterator(); it.hasNext();) {
                            Object object = it.next();
                            txtNomes.append(object.toString() + newline);
                        }
                    }

                    

//                } catch (FileNotFoundException ex) {
//                    //Logger.getLogger(FormPrincipal.class.getName()).log(Level.SEVERE, null, ex);
//                    txtLog.append(newline + "ERRO:" + ex.getMessage());
                } catch (ParserException parserException){
                    txtLog.append(newline + "ERRO:" + parserException.getMessage());                    
                }
               
                
            } else {
                txtLog.append("Comando cancelado pelo usuário." + newline);
            }
            txtLog.setCaretPosition(txtLog.getDocument().getLength());
        }
    }//GEN-LAST:event_btnAbrirActionPerformed

    private void criarArquivoTextoAuxiliar(String pathfile, String printStream) {
        FileOutputStream saida;
        PrintStream fileSaida;
        try {
            saida = new FileOutputStream(pathfile);
            fileSaida = new PrintStream(saida);
            fileSaida.print(printStream);
        } catch (Exception e) {
            System.err.println(e);
        }
    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FormPrincipal().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAbrir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea txtLog;
    private javax.swing.JTextArea txtNomes;
    private javax.swing.JTextField txtURL;
    // End of variables declaration//GEN-END:variables

}
